package org.jeecg.modules.hc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.enums.HcAfterSalesStateEnum;
import org.jeecg.modules.hc.enums.HcOrderStateEnum;
import org.jeecg.modules.hc.enums.HcWalletSourceEnum;
import org.jeecg.modules.hc.mapper.HcAfterSalesMapper;
import org.jeecg.modules.hc.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 售后
 * @Author: jeecg-boot
 * @Date: 2022-12-13
 * @Version: V1.0
 */
@Service
public class HcAfterSalesServiceImpl extends ServiceImpl<HcAfterSalesMapper, HcAfterSales> implements IHcAfterSalesService {

    @Autowired
    private IHcOrderDetailedService hcOrderDetailedService;

    @Lazy
    @Autowired
    private IHcWalletService hcWalletService;

    @Lazy
    @Autowired
    private IHcOrderMerchantService hcOrderMerchantService;

    @Resource
    private HcAfterSalesMapper hcAfterSalesMapper;

    @Override
    public IPage<HcAfterSales> getMerchantList(Page<HcAfterSales> page, HcAfterSales param) {
        return hcAfterSalesMapper.getMerchantList(page, param);
    }

    @Override
    public IPage<HcAfterSales> pageList(Page<HcAfterSales> page, HcAfterSales param) {
        IPage<HcAfterSales> pageList = hcAfterSalesMapper.pageList(page, param);

        for (HcAfterSales record : pageList.getRecords()) {
            this.setInformation(record);
        }

        return pageList;
    }

    public void setInformation(HcAfterSales param) {
        HcOrderDetailed hcOrderDetailed = hcOrderDetailedService.getOne(new QueryWrapper<HcOrderDetailed>()
                .select("GROUP_CONCAT(CONCAT(TRADE_NAME, 'x', COMMODITY_QUANTITY) Separator '+') as tradeName, SUM(COMMODITY_PRICE) as commodityPrice")
                .eq("AFTER_SALES_ID", param.getId())
        );

        if (hcOrderDetailed != null) {
            param.setNameDishes(hcOrderDetailed.getTradeName());
            param.setTotalPrice(hcOrderDetailed.getCommodityPrice());
        }

        param.setComplaintCount(this.count(new LambdaQueryWrapper<HcAfterSales>()
                .eq(HcAfterSales::getMerchantId, param.getMerchantId())
        ));

        HcOrderMerchant hcOrderMerchant = hcOrderMerchantService.getById(param.getOrderMerchantId());

        param.setHcOrderMerchant(hcOrderMerchant);
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(HcAfterSales hcAfterSales) {
        HcAfterSales afterSales = this.getById(hcAfterSales.getId());

        if (!afterSales.getState().equals(HcAfterSalesStateEnum.NO)) {
            throw new JeecgBootException("订单已处理");
        }

        HcAfterSales afterSalesUpd = new HcAfterSales();
        afterSalesUpd.setId(hcAfterSales.getId());
        afterSalesUpd.setState(hcAfterSales.getState());
        afterSalesUpd.setProcessingTime(new Date());

        if (hcAfterSales.getState().equals(HcAfterSalesStateEnum.YES)) {
            afterSalesUpd.setRefundAmount(hcAfterSales.getRefundAmount());
            afterSalesUpd.setDeductMerchantAmount(hcAfterSales.getDeductMerchantAmount());
            afterSalesUpd.setDeductionRemarks(hcAfterSales.getDeductionRemarks());

            if (hcAfterSales.getRefundAmount() != null && hcAfterSales.getRefundAmount().compareTo(new BigDecimal("0")) < 0) {
                throw new JeecgBootException("退款金额不能小于0！");
            }

            if (hcAfterSales.getDeductMerchantAmount() != null && hcAfterSales.getDeductMerchantAmount().compareTo(new BigDecimal("0")) < 0) {
                throw new JeecgBootException("扣除商家金额不能小于0！");
            }

            if (hcAfterSales.getRefundAmount() != null && hcAfterSales.getRefundAmount().compareTo(new BigDecimal("0")) > 0) {
                //钱包内增加余额
                hcWalletService.save(new HcWallet()
                        .setUserId(afterSales.getUserId())
                        .setAmount(hcAfterSales.getRefundAmount())
                        .setSource(HcWalletSourceEnum.AFTER_SALES)
                        .setRelationId(afterSalesUpd.getId())
                );
            }
        } else if (hcAfterSales.getState().equals(HcAfterSalesStateEnum.REJECT)) {
            if (StringUtils.isBlank(hcAfterSales.getReasonRejection())) {
                throw new JeecgBootException("请填写驳回原因");
            }

            afterSalesUpd.setReasonRejection(hcAfterSales.getReasonRejection());
        }

        this.updateById(afterSalesUpd);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(HcAfterSales param) {
        if (CollectionUtils.isEmpty(param.getHcOrderDetailedList())) {
            throw new JeecgBootException("菜品数据不能为空");
        }

        HcOrderMerchant hcOrderMerchant = hcOrderMerchantService.getById(param.getOrderMerchantId());

        if (!hcOrderMerchant.getState().equals(HcOrderStateEnum.PAY) && !hcOrderMerchant.getState().equals(HcOrderStateEnum.COMPLETED)) {
            throw new JeecgBootException("只有已付款和已完成订单才能申请售后");
        }

        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(hcOrderMerchant.getCreateTime());

        if (DateUtils.dateDiff('h', calendar1, calendar2) > 24) {
            throw new JeecgBootException("已超过24小时不能申请售后");
        }

        HcAfterSales hcAfterSales = new HcAfterSales()
                .setUserId(param.getUserId())
                .setMerchantId(hcOrderMerchant.getMerchantId())
                .setOrderMerchantId(param.getOrderMerchantId())
                .setFoodProblems(param.getFoodProblems())
                .setPicture(param.getPicture())
                .setFeedback(param.getFeedback())
                .setState(HcAfterSalesStateEnum.NO);

        this.save(hcAfterSales);

        //把售后id更新到商家订单中
        hcOrderMerchantService.updateById(new HcOrderMerchant().setId(param.getOrderMerchantId()).setAfterSalesId(hcAfterSales.getId()));

        //把售后id更新到订单明细中
        for (HcOrderDetailed hcOrderDetailed : param.getHcOrderDetailedList()) {
            hcOrderDetailedService.updateById(new HcOrderDetailed().setId(hcOrderDetailed.getId()).setAfterSalesId(hcAfterSales.getId()));
        }
    }
}
